package com.cqc.lite.service.impl;

import com.cqc.lite.dao.RoleDao;
import com.cqc.lite.dao.UserDao;
import com.cqc.lite.domain.Role;
import com.cqc.lite.domain.UserInfo;
import com.cqc.lite.service.UserService;
import com.cqc.lite.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 必须命名，否则user-service-ref="userService" 不知道引用谁
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

    private final UserDao userDao;
    private final PasswordEncoder passwordEncoder;
    @Autowired
    public UserServiceImpl(UserDao userDao,PasswordEncoder passwordEncoder){
        this.userDao=userDao;
        this.passwordEncoder=passwordEncoder;
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据name获取UserInfo对象
        UserInfo userInfo = null;
        try {
            userInfo = userDao.findUserByUsername(username);
        }catch (Exception e){
            e.printStackTrace();
        }
        //获取角色列表List<Role>  获取简单权限
        User user = new User(userInfo.getUsername(),userInfo.getPassword(),
                userInfo.getStatus() == 0 ? false : true,
                true, true, true,
                getAuthority(userInfo.getRoles()));
        return user;
    }
    private List<SimpleGrantedAuthority> getAuthority(List<Role> roles) {
        List<SimpleGrantedAuthority> list=new ArrayList<>();
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
        }
        return list;
    }

    @Override
    public List<UserInfo> findAll() {
        return userDao.findAll();
    }

    @Override
    public int save(UserInfo userInfo) {
        userInfo.setId(UUIDUtils.getId());
        userInfo.setPassword(passwordEncoder.encode(userInfo.getPassword()));
        return userDao.save(userInfo);
    }

    @Override
    public UserInfo findById(String id) {
        return userDao.findById(id);
    }

    @Override
    public void addRoleToUser(String userId, List<String> roleIdList) {
        //删除旧关系
        userDao.deleteUserRoleByUserId(userId);
        //新增 关系
        for (int i = 0; i < roleIdList.size(); i++) {
            userDao.insertUserRole(userId,roleIdList.get(i));
        }
    }
}
